package com.sixmac.controller;


import com.sixmac.annotation.AuthUser;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.constant.ConstConfig;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.RandomKit;
import com.sixmac.module.DayMoney;
import com.sixmac.module.Pay;
import com.sixmac.module.Tenant;
import com.sixmac.module.TenantRoom;
import com.sixmac.util.WeChatCallBack;
import com.thoughtworks.xstream.XStream;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpPayCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zjx
 */
@Controller
@ResponseBody
@RequestMapping("/paymentWay")
public class PaymentApi extends BaseController {

    @Autowired
    WxMpService wxMpService;

    /**
     * @api {post}  /api/paymentWay/payStatus 01.支付
     * @apiName paymentWay.payStatus
     * @apiGroup paymentWay
     * @apiParam {String} json              用户token（必传）
     * @apiParam {String} money             金额（必传）
     * @apiParam {String} unionId           第三方登录识别（必传）
     * @apiParam {Integer} type             1：延保卡支付 2：积分产品支付  3：售后服务支付 （必传）
     * @apiParam {String} orderNo           订单号 （必传）
     * @apiSuccess {Object}   date
     * @apiSuccess {Integer}  date.code    0：成功 1：失败
     * @apiSuccess {String}   date.message  返回消息
     */
    @AuthUser
    @RequestMapping("/payStatus")
    public AjaxResult toPay(Tenant tenant, BigDecimal money, String unionId, Integer type, String orderNo) {
        System.out.println("----orderNo：" + orderNo + "-------");
        Double payMoney = money.doubleValue();

        Map<String, String> result = wxMpService.getJSSDKPayInfo(unionId, orderNo, payMoney, "亿云智锁", "JSAPI",
                getRequest().getRemoteAddr(), "http://6mai.mynatapp.cc/tenant/paymentWay/callback?userId=" + tenant.getId() + "&type=" + type);
       return json(result);
    }

    @AuthUser
    @RequestMapping("/getlocks")
    public AjaxResult getLocks(Tenant tenant){
        return json(Blade.create(DayMoney.class).findAll());
    }

    @AuthUser
    @RequestMapping("/getOrder")
    public AjaxResult getOrder(Tenant tenant,Integer dayId){
        String orderId =  DateKit.getAllTime()+ RandomKit.randomNumbers(2)+""+tenant.getId();
        HashMap<String,Object> days = new HashMap<>();
        days.put("orderId",orderId);
        days.put("dayId",dayId);
        DayMoney dayMoney = Blade.create(DayMoney.class).findById(dayId);
        if (dayMoney==null){
            return fail("价格选择错误");
        }
        days.put("money",dayMoney.getMoney());
        Pay pay = new Pay();
        pay.setCreatTime(new Date());
        pay.setDayId(dayId);
        pay.setOrderNum(orderId);
        pay.setMoney(dayMoney.getMoney());
        pay.setStatus(0);
        pay.setTenantId(tenant.getId());
        pay.setIsDo(0);
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+tenant.getId(),null);
        days.put("openId",tenant.getWechatKey());
        pay.setTrId(tenantRoom.getId());
        Blade.create(Pay.class).save(pay);
        return json(days);
    }

    @AuthUser
    @RequestMapping("/getLock")
    public AjaxResult getLock(Tenant tenant,String orderNo){
        Pay pay = Blade.create(Pay.class).findFirstBy(" orderNum='"+orderNo+"'",null);
        if (pay.getIsDo() == 1){
            return fail("该订单已经录入指纹");
        }
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findById(pay.getTrId());
        HashMap<String,Object> data = new HashMap<>();
        DayMoney dayMoney = Blade.create(DayMoney.class).findById(pay.getDayId());
        if (tenantRoom.getFingerprint() ==null){
            data.put("isNew",1);//新增
            pay.setStartTime(new Date());
            pay.setEndTime(DateKit.getAfterDayDate(new Date(),dayMoney.getDay()));
            data.put("pay",pay);
        }else{
            data.put("isNew",2);//编辑
            data.put("lockNum",tenantRoom.getFingerprint());
            pay.setStartTime(tenantRoom.getLockStartTime());
            pay.setEndTime(DateKit.getAfterDayDate(tenantRoom.getLockEndTime(),dayMoney.getDay()));
            data.put("pay",pay);
        }
        return json(data);
    }

    @RequestMapping(value = "/callback")
    public Object callBack() {

        try {

            //把如下代码贴到的你的处理回调的servlet 或者.do 中即可明白回调操作
            System.out.print("微信支付回调数据开始");
            String inputLine;
            String notityXml = "";
            try {
                while ((inputLine = getRequest().getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                getRequest().getReader().close();
            } catch (Exception e) {
                System.out.println("----------");
                String xmlResult = "<xml>" +
                        "<return_code><![CDATA[FAIL]]></return_code>" +
                        "<return_msg><![CDATA[支付失败，请重试]]></return_msg>" +
                        "</xml>";
                return xmlResult;
            }

            System.out.println("接收到的报文：" + notityXml);

            System.out.println("接收到的报文：" + notityXml);

            XStream xstream = XStreamInitializer.getInstance();
            xstream.alias("xml", WeChatCallBack.class);
            WeChatCallBack weChatCallBack = (WeChatCallBack) xstream.fromXML(notityXml);

            Integer userId = null;
            Integer type = null;

            if(!weChatCallBack.getUserId().equals("null")){
                userId = Integer.parseInt(weChatCallBack.getUserId());
            }

            if(!weChatCallBack.getType().equals("null")){
                type = weChatCallBack.getType();
            }

            System.out.println(userId+"----------");
            System.out.println(type+"----------");

            WxMpPayCallback wxMpPayCallback = wxMpService.getJSSDKCallbackData(notityXml);

            //判断支付成功，更改订单状态
            if ("SUCCESS".equals(wxMpPayCallback.getReturn_code())) {
                System.out.println("--------------------------");
                System.out.println(wxMpPayCallback.toString());
                System.out.println("--------------------------");
//                ClientUser user = clientUserService.findById(userId);
                String orderNo = wxMpPayCallback.getOut_trade_no();
                //获取支付回调订单信息
                Double money = Double.valueOf(wxMpPayCallback.getTotal_fee()) / 100;
                Pay pay = Blade.create(Pay.class).findFirstBy(" orderNum='"+orderNo+"'",null);


                if (pay!=null){
                    TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+pay.getTenantId(),null);
                    DayMoney dayMoney = Blade.create(DayMoney.class).findById(pay.getDayId());
                    if (tenantRoom!=null){
                        tenantRoom.setDeleteStatus(0);
                        Blade.create(TenantRoom.class).update(tenantRoom);
                    }
                    pay.setStatus(1);
                    pay.setMoney(new BigDecimal(money));
                    pay.setPayTime(new Date());
                    Blade.create(Pay.class).update(pay);
                }
                //修改用户积分、余额、优惠卷
            } else {
                System.out.println("----------");
                System.out.println(wxMpPayCallback);
                String xmlResult = "<xml>" +
                        "<return_code><![CDATA[FAIL]]></return_code>" +
                        "<return_msg><![CDATA[支付失败，请重试]]></return_msg>" +
                        "</xml>";
                return xmlResult;
            }

            System.out.println("----------");
            System.out.println(wxMpPayCallback);
            String xmlResult = "<xml>" +
                    "<return_code><![CDATA[SUCCESS]]></return_code>" +
                    "<return_msg><![CDATA[OK]]></return_msg>" +
                    "</xml>";
            return xmlResult;
        } catch (Exception e) {
            System.out.println("----------");
            String xmlResult = "<xml>" +
                    "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[支付失败，请重试]]></return_msg>" +
                    "</xml>";
            return xmlResult;
        }
    }
}

